package com.stu.stusystem.service.chat;

import com.stu.stusystem.common.ApiException;
import com.stu.stusystem.mapper.chat.ChatFriendsMapper;
import com.stu.stusystem.mapper.system.StuMapper;
import com.stu.stusystem.model.chat.ChatFriends;
import com.stu.stusystem.model.system.StuUser;
import com.stu.stusystem.service.system.vo.StuUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: cxt
 * @time: 2021/6/15
 */
@Service
public class ChatFriendsService {

    private ChatFriendsMapper chatFriendsMapper;

    private StuMapper stuMapper;

    /**
     * 查询列表
     */
    public List<StuUserVO> getFriends(String id) {
        return this.chatFriendsMapper.getFriends(id);
    }

    /**
     * 待添加列表
     */
    public List<StuUserVO> getStay(String id) {
        return this.chatFriendsMapper.getStay(id);
    }

    /**
     * 添加
     */
    public void add(ChatFriends chatFriends) {
        String fId = chatFriends.getFriendsId();
        String[] split = fId.split(",");
        if (split.length > 1) {
            List<String> fid = this.chatFriendsMapper.getFid();
            List<String> resultList = new ArrayList<>(Arrays.asList(split));
            if (!fid.containsAll(resultList)) {
                throw new ApiException("好友id非法,刷新重试");
            }
            int i = this.chatFriendsMapper.addFriends(chatFriends.getId(), split);
            if (i == 0) {
                throw new ApiException(ApiException.SAVE_FAIL);
            }
        } else {
            StuUser user = this.stuMapper.selectByPrimaryKey(chatFriends.getFriendsId());
            if (user == null) {
                throw new ApiException("好友id非法,刷新重试");
            }
            int insert = this.chatFriendsMapper.insert(chatFriends);
            if (insert == 0) {
                throw new ApiException(ApiException.SAVE_FAIL);
            }
        }
    }

    /**
     * 删除好友
     */
    public void removeFriend(String id, String fId) {
        int i = this.chatFriendsMapper.removeFriend(id, fId);
        if (i == 0) {
            throw new ApiException(ApiException.DELETE_FAIL);
        }
    }

    @Autowired
    public void setChatFriendsMapper(ChatFriendsMapper chatFriendsMapper) {
        this.chatFriendsMapper = chatFriendsMapper;
    }

    @Autowired
    public void setStuMapper(StuMapper stuMapper) {
        this.stuMapper = stuMapper;
    }
}
